import { Box, Button, Checkbox, IconButton, InputAdornment, Table, TableBody, TableContainer, TableFooter, TableHead, TableRow, TextField } from "@mui/material";
import React, { JSX } from "react";
import '@fontsource/open-sans';
import { ReactComponent as CreateIcon } from '../../assets/create.svg';
import { ReactComponent as SearchIcon } from '../../assets/search.svg';
import DeleteIcon from '@mui/icons-material/Delete';
import ClearIcon from '@mui/icons-material/Clear';
import { useAppDispatch, useAppSelector } from "../../actions/hook";
import { removeElementFromArray } from "../../util/Arrays";
import { fetchAllUserEntries, UserEntry, deleteUser, selectUserEntries, selectUserFetched } from "../../actions/UserManagement";
import EditIcon from '@mui/icons-material/Edit';
import { CreateUser } from "../UserManagementDialog/CreateUser";
import { ModifyUser } from "../UserManagementDialog/ModifyUser";
import { NulHeaderTableCell, NulTableCell } from "../../components/NulHeaderTable";

const genderMap: Map<string, string> = new Map<string, string>([
  ['male', 'Male'],
  ['female', 'Female']
]);

const authorityMap: Map<string, string> = new Map<string, string>([
  ['admin', 'Administrator'],
  ['user', 'User']
]);

interface UserManagementProps {
  show: boolean;
}

function UserManagement(props: UserManagementProps): JSX.Element {

  const [filterValue, setFilterValue] = React.useState<string>('');
  const [openUserDialog, setOpenUserDialog] = React.useState<boolean>(false);
  const [openModifyDialog, setOpenModifyDialog] = React.useState<boolean>(false);
  const [modifyUserEntry, setModifyUserEntry] = React.useState<UserEntry>({
    id: 0, name: '', userName: '', gender: '', authority: ''
  });

  const fetchedUserEntries = useAppSelector(selectUserFetched);
  const UserEntries = useAppSelector(selectUserEntries);
  const [filteredUserEntries, setFilteredUserEntries] = React.useState<UserEntry[]>([]);
  const [checkedIdList, setCheckedIdList] = React.useState<number[]>([]);

  const dispatch = useAppDispatch();

  const transformGender = (raw: string): string => {
    let result: string | undefined = genderMap.get(raw);
    if (result === undefined) {
      result = '';
    }
    return result;
  }

  const transformAuthority = (raw: string): string => {
    let result: string | undefined = authorityMap.get(raw);
    if (result === undefined) {
      result = '';
    }
    return result;
  }

  React.useEffect(() => {
    if (!fetchedUserEntries) {
      dispatch(fetchAllUserEntries());
    }
  });

  const handleModify = (row: UserEntry) => {
    setModifyUserEntry(row);
    setOpenModifyDialog(true);
  };

  const handleDelete = (row: UserEntry) => {
    dispatch(deleteUser([row.id]));
  };

  React.useEffect(() => {
    if (UserEntries !== undefined) {
      setFilteredUserEntries(UserEntries.filter(val => val !== undefined && val.userName.indexOf(filterValue) !== -1));
      setCheckedIdList([]);
    }
  }, [UserEntries, filterValue]);

  const headerChecked: boolean = checkedIdList.length !== 0 && checkedIdList.length === filteredUserEntries.length;
  const headerIndeterminate: boolean = checkedIdList.length !== 0 && checkedIdList.length < filteredUserEntries.length;

  if (!props.show) {
    return <></>;
  }
  return (
    <>
      <Box sx={{ padding: '30px 30px 30px 30px', flex: 'none', flexGrow: 1 }}>
        <Box sx={{
          fontFamily: 'Open Sans',
          fontStyle: 'normal',
          fontWeight: 600,
          fontSize: '22px',
          lineHeight: '125%'
        }}>
          User Management
        </Box>
        <Box sx={{
          marginTop: '20px', width: '100%', height: '40px', display: 'flex',
          flexDirection: 'row', justifyContent: 'space-between'
        }}>
          <Box sx={{ width: '456px' }}>
            <TextField
              size='small'
              fullWidth={true}
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start' sx={{}}>
                    <SearchIcon />
                  </InputAdornment>
                ),
                endAdornment: (
                  <IconButton edge="end" onClick={() => { setFilterValue(''); }}>
                    <ClearIcon fontSize='small' />
                  </IconButton>
                )
              }}
              placeholder='Search user'
              value={filterValue}
              onChange={(action) => { setFilterValue(action.target.value); }}
              sx={{
                paddingLeft: '0px'
              }}
            />
          </Box>
          <Box sx={{
            flex: 'none',
            order: 1,
            flexGrow: 0
          }}>
            <Button
              variant="contained"
              disableElevation
              startIcon={<CreateIcon />}
              onClick={() => {
                setOpenUserDialog(true);
              }}
              sx={{
                height: '40px',
                textTransform: 'none'
              }}
            >
              Create
            </Button>
          </Box>
        </Box>
        <Box sx={{
          marginTop: '20px',
          width: '100%'
        }}>
          <TableContainer
            sx={{
              width: '100%'
            }}
          >
            <Table
              stickyHeader
              sx={{
                border: '1px solid #DFE4E8',
                borderRadius: '8px',
                fontFamily: 'Open Sans',
                fontStyle: 'normal',
              }}
            >
              <TableHead sx={{ border: '8px 8px 0px 0px' }}>
                <TableRow sx={{
                  height: '42px',
                  padding: 0,
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                }}>
                  <Box sx={{ height: '100%' }}>
                    <NulHeaderTableCell
                      sx={{
                        width: '62px',
                        borderTopLeftRadius: '8px',
                        justifyContent: 'center',
                        flexGrow: 0
                      }}
                    >
                      <Checkbox
                        sx={{
                          width: '42px',
                          display: 'flex',
                          justifyContent: 'center',
                        }}
                        onClick={() => {
                          if (headerChecked) {
                            setCheckedIdList([]);
                          }
                          else {
                            setCheckedIdList(filteredUserEntries.map(entry => entry.id));
                          }
                        }}
                        checked={headerChecked}
                        indeterminate={headerIndeterminate}
                      />
                    </NulHeaderTableCell>
                  </Box>
                  <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%' }}>
                    <NulHeaderTableCell sx={{ width: '7%' }}>
                      UID
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '15%' }}>
                      User Name
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '18%' }}>
                      Name
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '15%' }}>
                      Gender
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '20%' }}>
                      Authority
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '25%' }}>
                      Operations
                    </NulHeaderTableCell>
                  </Box>
                </TableRow>
              </TableHead>
              <TableBody
                sx={{
                  minHeight: '400px', display: 'block', overflowY: 'auto'
                }}
              >
                {filteredUserEntries.map(row => {
                  const checkedIndex: number = checkedIdList.indexOf(row.id);
                  return (
                    <TableRow
                      key={row.id}
                      sx={{
                        width: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        height: '42px'
                      }}
                    >
                      <Box sx={{ height: '100%' }}>
                        <NulTableCell sx={{ width: '62px', justifyContent: 'center', flexGrow: 0 }}>
                          <Checkbox
                            sx={{
                              width: '42px',
                              display: 'flex',
                              justifyContent: 'center',
                            }}
                            checked={checkedIndex !== -1}
                            onChange={(event, checked) => {
                              if (checked) {
                                if (checkedIndex === -1) {
                                  setCheckedIdList([...checkedIdList, row.id]);
                                }
                              }
                              else {
                                if (checkedIndex !== -1) {
                                  setCheckedIdList(removeElementFromArray(checkedIdList, checkedIndex));
                                }
                              }
                            }}
                          />
                        </NulTableCell>
                      </Box>
                      <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%' }}>
                        <NulTableCell sx={{ width: '7%' }}>
                          {row.id}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '15%' }}>
                          {row.userName}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '18%' }}>
                          {row.name}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '15%' }}>
                          {transformGender(row.gender)}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '20%' }}>
                          {transformAuthority(row.authority)}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '25%', display: 'flex' }}>
                          <IconButton aria-label='edit' onClick={() => { handleModify(row); }}>
                            <EditIcon />
                          </IconButton>
                          <IconButton aria-label='delete' onClick={() => { handleDelete(row); }}>
                            <DeleteIcon />
                          </IconButton>
                        </NulTableCell>
                      </Box>
                    </TableRow>
                  );
                })}
              </TableBody>
              <TableFooter
                sx={{
                  minHeight: '34px',
                  maxHeight: '44px',
                  display: 'block',
                  backgroundColor: '#F1F3F5',
                  borderRadius: '0px 0px 8px 8px',
                }}
              ></TableFooter>
            </Table>
          </TableContainer>
        </Box>
      </Box>
      <CreateUser
        open={openUserDialog}
        onClose={() => { setOpenUserDialog(false); }}
      />
      <ModifyUser
        open={openModifyDialog}
        customerEntry={modifyUserEntry}
        onClose={() => { setOpenModifyDialog(false); }}
      />
    </>
  );
}

export default UserManagement;